import React, { useEffect, useState } from 'react';
import Modals from '@/components/modals/Modals';
import { Form, Input, InputNumber, ModalProps, Select, SelectProps } from 'antd';
import { GetCreatedListItem, GetModelListModels, GetProviderListItem } from '@/common';
import modelService from '@/api/services/modelService';
import ModalsFooterBtn from '@/components/modals/ModalsFooterBtn';
import TipsModals from '@/components/modals/TipsModals';
import useModal from '@/hooks/use-modal/useModal';
import { SvgIcon } from '@/components/icon';

interface Props extends ModalProps {
  open: boolean;
  onCancel: () => void;
  onOk: () => void;
  modelData: GetProviderListItem | GetCreatedListItem | undefined;
  defaultValue: GetModelListModels | undefined;
  onClose?: () => void;
  userInput?: any;
  customStatus?: boolean;
  setList?: (data: any) => void;
  hanldeDeleteSetList?: (data: any) => void;
  listNumber?: number;
  closeInput?: (value?: boolean) => void;
}

const index = ({
  onOk,
  modelData,
  defaultValue,
  onCancel,
  onClose,
  userInput,
  customStatus,
  setList,
  hanldeDeleteSetList,
  listNumber,
  closeInput,
  ...props
}: Props) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const modal = useModal('tips');

  const [verticalStatus, setVerticalStatus] = useState(false);
  const [errorMsg, setErrorMsg] = useState<string>('');

  useEffect(() => {
    if (defaultValue) {
      let enableReasoning: any = 0;
      if (!defaultValue.metadata.reasoning) {
        enableReasoning = 0;
      } else if (defaultValue.metadata.onlyThinkMode) {
        enableReasoning = false;
      } else {
        enableReasoning = true;
      }

      form.setFieldsValue({
        modelType: defaultValue.metadata.type,
        name: defaultValue.metadata.model,
        maxContext: defaultValue.metadata.maxContext,
        maxResponse: defaultValue.metadata.maxResponse,
        usedInToolCall: defaultValue.metadata.usedInToolCall,
        enableReasoning: enableReasoning,
      });
    } else {
      form.resetFields();
      setVerticalStatus(false);
      setErrorMsg('');
    }
  }, [defaultValue]);

  const modeleType = [
    {
      label: '语言模型',
      value: 'llm',
    },
    {
      label: '工具调用模型',
      value: 'funcCall',
    },
    {
      label: '重排模型',
      value: 'rerank',
    },
    {
      label: '索引模型',
      value: 'embedding',
    },
    {
      label: '非默认模型',
      value: 'non',
    },
    {
      label: '语音模型',
      value: 'tt',
    },
    {
      label: '语音转文本模型',
      value: 'stt',
    },
    {
      label: '文本转语音模型',
      value: 'tts',
    },
  ];

  const modelFunction = [
    {
      label: '支持',
      value: true,
    },
    {
      label: '不支持',
      value: false,
    },
  ];

  const enableReasoningFunction = [
    {
      label: '支持',
      value: true,
    },
    {
      label: '不支持',
      value: 0,
    },
    {
      label: '仅支持',
      value: false,
    },
  ];

  const onSubmit = (value: any) => {
    if (customStatus) {
      let result = {
        key: userInput.key,
        address: userInput.baseUrl,
        name: value.name,
        modelType: value.modelType,
      };

      modelService.customTest(result).then((res) => {
        if (res) {
          setVerticalStatus(true);
          setErrorMsg(res);
          // form.setFields([
          //   {
          //     name: 'name',
          //     errors: ['模型已存在，无法重复添加'],
          //   },
          // ]);
          return;
        }
        setList && setList(value);
        handleClose();
      });

      return;
    }
    setLoading(true);
    const api = defaultValue ? modelService.updateProviderModel : modelService.createProviderModel;
    let result = {
      ...value,
      providerId: modelData?.id,
      providerName: modelData?.name,
      key: userInput.key,
      address: userInput.baseUrl,
    };

    if (value.enableReasoning === 0) {
      delete result.enableReasoning;
    }

    api(result)
      .then((res) => {
        console.log(res);
        if (res) {
          setVerticalStatus(true);
          setErrorMsg(res);
          // form.setFields([
          //   {
          //     name: 'name',
          //     errors: ['模型已存在，无法重复添加'],
          //   },
          // ]);
          return;
        }
        onOk();
      })
      .finally(() => {
        setLoading(false);
      });
  };

  const handleClose = () => {
    onCancel();
    form.resetFields();
    setVerticalStatus(false);
    setErrorMsg('');
  };

  const handleDeleteModel = () => {
    if (customStatus) {
      hanldeDeleteSetList && hanldeDeleteSetList(defaultValue);
      modal.tips.close();
      if (listNumber && listNumber === 1) {
        closeInput && closeInput(true);
      }
      return;
    }

    modal.tips.startLoading();
    modelService
      .deleteProviderModel({
        providerId: modelData?.id as string,
        providerName: modelData?.name as string,
        name: defaultValue?.name as string,
      })
      .then((res) => {
        handleClose();
        // console.log(res);
        modal.tips.close();
        onOk();
        if (listNumber && listNumber <= 1) {
          closeInput && closeInput(true);
        }
      })
      .finally(() => {
        modal.tips.stopLoading();
      });
  };

  const ModalsFooter = () => {
    return (
      <div
        className="flex items-center justify-between px-4 py-3"
        style={{
          borderTop: '1px solid #E5E6EB',
        }}
      >
        {defaultValue && (
          <ModalsFooterBtn danger onClick={modal.tips.open}>
            删除模型
          </ModalsFooterBtn>
        )}
        <div className="flex flex-1 justify-end gap-3">
          <ModalsFooterBtn onClick={handleClose}>取消</ModalsFooterBtn>
          <ModalsFooterBtn type="primary" onClick={form.submit} loading={loading}>
            确定
          </ModalsFooterBtn>
        </div>
      </div>
    );
  };

  const handleText = () => {
    if (listNumber && listNumber <= 1) {
      return `${
        defaultValue && defaultValue?.usedCount > 0
          ? `该模型已被${defaultValue?.usedCount}个应用使用，删除后这些应用将无法正常使用。`
          : ''
      }此模型为该厂商下最后一个模型，删除后将一并清除厂商信息。`;
    } else if (defaultValue && defaultValue?.usedCount > 0) {
      return `该模型已被${defaultValue.usedCount}个应用使用，会影响当前应用效果，确认删除？`;
    }
    return '确认删除该模型，删除后无法恢复';
  };

  return (
    <>
      <Modals
        {...props}
        footer={<ModalsFooter />}
        onOk={form.submit}
        onCancel={handleClose}
        title="添加模型"
        confirmLoading={loading}
        onClose={onClose}
      >
        {verticalStatus && (
          <div className="mb-2 flex items-center rounded-md border-[1px] border-solid border-@error-color py-1 text-xs leading-5 text-@error-color">
            <SvgIcon icon="warning" size={16} className="mx-2" color="#FC5151" />
            <div>{errorMsg}</div>
          </div>
        )}

        <Form layout="vertical" form={form} onFinish={onSubmit}>
          <Form.Item
            label="模型类型"
            name="modelType"
            rules={[{ required: true, message: '请选择模型类型' }]}
          >
            <Select options={modeleType} />
          </Form.Item>
          <Form.Item
            label="模型名称"
            name="name"
            rules={[{ required: true, message: '请输入模型名称' }]}
          >
            <Input disabled={defaultValue ? true : false} />
          </Form.Item>
          <Form.Item
            label="模型上下文长度"
            name="maxContext"
            rules={[{ required: true, message: '请输入模型上下文长度' }]}
          >
            <InputNumber min={1000} controls={false} style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            label="最大token上限"
            name="maxResponse"
            rules={[{ required: true, message: '请输入最大token上限' }]}
          >
            <InputNumber min={1000} controls={false} style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            label="是否支持工具调用"
            name="usedInToolCall"
            rules={[{ required: true, message: '请选择工具调用' }]}
          >
            <Select options={modelFunction} />
          </Form.Item>
          <Form.Item
            label="是否支持深度思考"
            name="enableReasoning"
            rules={[{ required: true, message: '请选择深度思考' }]}
          >
            <Select options={enableReasoningFunction} />
          </Form.Item>
        </Form>
      </Modals>

      <TipsModals
        open={modal.tips.isOpen}
        onCancel={modal.tips.close}
        onOk={handleDeleteModel}
        confirmLoading={modal.tips.isLoading}
      >
        {/* {defaultValue && defaultValue?.usedCount > 0
          ? `该模型已被${defaultValue.usedCount}个应用使用，会影响当前应用效果，确认删除？`
          : '确认删除该模型，删除后无法恢复'} */}
        {handleText()}
      </TipsModals>
    </>
  );
};

export default index;
